﻿using System.CodeDom;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using AutoUnitTest.Common;

namespace AutoUnitTest.Common.CodeGeneration.CS
{
    public class MsTestGenerator : ClassGenerator
    {
        public override void CreateClass(string className, string nameSpace = null)
        {
            base.CreateClass(className+"Test", nameSpace);
            Namespace.Imports.Add(new CodeNamespaceImport("Microsoft.VisualStudio.TestTools.UnitTesting"));
            Class.CustomAttributes.Add(new CodeAttributeDeclaration("TestClass"));
        }

        public override void AddMethod(string methodName,
            MethodParameter returnValue = null,
            MemberAttributes methodAccess = MemberAttributes.Assembly | MemberAttributes.Final,
            params MethodParameter[] methodParameters)
        {
            string convertedMethodNameForTest = TestMethodNameConversion(methodName,methodParameters);

            base.AddMethod(convertedMethodNameForTest, returnValue, methodAccess, null);


            var method = Methods.FirstOrDefault(m => m.Name == convertedMethodNameForTest);

            if(method != null)
                method.CustomAttributes.Add(new CodeAttributeDeclaration("TestMethod"));

            // TODO: iterate params and add test each case
        }

        private string TestMethodNameConversion(string methodName, MethodParameter[] methodParameters)
        {
            var convertedName = new StringBuilder();
            convertedName.Append(methodName);
            foreach (MethodParameter methodParameter in methodParameters)
            {
                convertedName.AppendFormat("_{1}Of{0}_",
                    methodParameter.Type != null 
                        ? methodParameter.Type.ToString().Type()
                        : methodParameter.TypeAsString.Type(),
                    methodParameter.Name);
            }
            convertedName.Append("Test");
            return convertedName.ToString();
        }
    }
}
